<template>
  <div class="user-edit">
    <!-- 头部导航 -->
    <el-card class="header-card" shadow="hover">
      <div class="header-content">
        <div class="header-left">
          <el-button type="primary" @click="goBack" plain>
            <el-icon><ArrowLeft /></el-icon>
            返回列表
          </el-button>
          <el-divider direction="vertical" />
          <el-icon class="header-icon"><Edit /></el-icon>
          <span class="header-title">编辑用户</span>
        </div>
        <div class="header-actions">
          <el-button type="info" @click="handleView">
            <el-icon><View /></el-icon>
            查看详情
          </el-button>
        </div>
      </div>
    </el-card>

    <el-row :gutter="20">
      <!-- 编辑表单 -->
      <el-col :span="16">
        <el-card class="form-card" shadow="hover" v-loading="loading">
          <template #header>
            <div class="card-header">
              <el-icon><Document /></el-icon>
              <span>用户信息编辑</span>
            </div>
          </template>

          <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="120px"
            label-position="top"
            class="user-form"
          >
            <!-- 基本信息 -->
            <div class="form-section">
              <div class="section-title">
                <el-icon><User /></el-icon>
                <span>基本信息</span>
              </div>
              
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="用户名" prop="username">
                    <el-input
                      v-model="form.username"
                      placeholder="请输入用户名"
                      prefix-icon="User"
                      clearable
                    />
                    <div class="form-tip">用户名可以修改，但建议保持唯一性</div>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="密码" prop="password">
                    <el-input
                      v-model="form.password"
                      type="password"
                      placeholder="请输入新密码（留空则不修改）"
                      prefix-icon="Lock"
                      clearable
                      show-password
                    />
                    <div class="form-tip">留空则不修改原密码</div>
                  </el-form-item>
                </el-col>
              </el-row>

                        <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="手机号码" prop="mobile">
                <el-input
                  v-model="form.mobile"
                  placeholder="请输入手机号码"
                  prefix-icon="Phone"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="性别" prop="gender">
                <el-radio-group v-model="form.gender">
                  <el-radio label="male">
                    <el-icon><Male /></el-icon>
                    男
                  </el-radio>
                  <el-radio label="female">
                    <el-icon><Female /></el-icon>
                    女
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="头像" prop="avatar">
                    <div class="avatar-upload-container">
                      <el-avatar 
                        :src="form.avatar || '/src/assets/images/default-avatar.png'" 
                        :size="60" 
                        class="avatar-preview"
                      >
                        {{ form.username?.charAt(0) || 'U' }}
                      </el-avatar>
                      <div class="avatar-upload-actions">
                                              <el-upload
                        ref="avatarUploadRef"
                        action="#"
                        :show-file-list="false"
                        :before-upload="beforeAvatarUpload"
                        :http-request="handleAvatarUpload"
                        accept="image/*"
                        class="avatar-uploader"
                      >
                        <el-button type="primary" size="small">
                          <el-icon><Upload /></el-icon>
                          上传头像
                        </el-button>
                      </el-upload>
                        <el-button 
                          v-if="form.avatar" 
                          type="danger" 
                          size="small" 
                          @click="removeAvatar"
                        >
                          <el-icon><Delete /></el-icon>
                          删除
                        </el-button>
                      </div>
                    </div>
                    <div class="form-tip">支持 JPG、PNG、GIF 格式，文件大小不超过 5MB</div>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>

            <!-- 联系信息 -->
            <div class="form-section">
              <div class="section-title">
                <el-icon><Phone /></el-icon>
                <span>联系信息</span>
              </div>
              
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="邮箱" prop="email">
                    <el-input
                      v-model="form.email"
                      placeholder="请输入邮箱地址"
                      prefix-icon="Message"
                      clearable
                    />
                  </el-form-item>
                </el-col>

              </el-row>


            </div>

            <!-- 角色分配 -->
            <div class="form-section">
              <div class="section-title">
                <el-icon><UserFilled /></el-icon>
                <span>角色分配</span>
              </div>
              
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="角色" prop="roleIds">
                    <el-select
                      v-model="form.roleIds"
                      placeholder="请选择角色"
                      style="width: 100%;"
                      clearable
                      multiple
                    >
                      <el-option
                        v-for="role in roleOptions"
                        :key="role.id"
                        :label="role.name"
                        :value="role.id"
                      >
                        <span style="float: left">{{ role.name }}</span>
                        <span style="float: right; color: #8492a6; font-size: 13px">
                          {{ role.id }}
                        </span>
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                            <el-col :span="12">
              <el-form-item label="所属客户" prop="customerId">
                <el-select
                  v-model="form.customerId"
                  placeholder="请选择客户"
                  style="width: 100%;"
                  clearable
                  :disabled="isSystemAdmin"
                  :required="!isSystemAdmin"
                >
                  <el-option
                    v-for="customer in customerOptions"
                    :key="customer.id"
                    :label="customer.name"
                    :value="customer.id"
                  />
                </el-select>
                <div class="form-tip" v-if="isSystemAdmin">
                  系统管理员无需选择客户
                </div>
                <div class="form-tip" v-else>
                  请选择所属客户
                </div>
              </el-form-item>
            </el-col>
              </el-row>
            </div>

            <!-- 状态设置 -->
            <div class="form-section">
              <div class="section-title">
                <el-icon><Setting /></el-icon>
                <span>状态设置</span>
              </div>
              
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="账户状态" prop="status">
                    <el-radio-group v-model="form.status">
                      <el-radio label="enabled">
                        <el-tag type="success" size="small">启用</el-tag>
                      </el-radio>
                      <el-radio label="disabled">
                        <el-tag type="danger" size="small">禁用</el-tag>
                      </el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>



            <!-- 操作按钮 -->
            <div class="form-actions">
              <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
                <el-icon><Check /></el-icon>
                保存修改
              </el-button>
              <el-button @click="handleReset">
                <el-icon><RefreshLeft /></el-icon>
                重置表单
              </el-button>
              <el-button type="info" @click="goBack">
                <el-icon><Close /></el-icon>
                取消编辑
              </el-button>
            </div>
          </el-form>
        </el-card>
      </el-col>

      <!-- 侧边预览 -->
      <el-col :span="8">
        <!-- 当前用户预览 -->
        <el-card class="preview-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon><View /></el-icon>
              <span>用户预览</span>
            </div>
          </template>
          
          <div class="user-preview">
            <el-avatar
              :src="form.avatar"
              :size="80"
              class="preview-avatar"
            >
              {{ form.username?.charAt(0) }}
            </el-avatar>
            
            <div class="preview-info">
              <h4>{{ form.username }}</h4>
              <p class="preview-role">{{ currentRoleName || '暂无角色' }}</p>
              <p class="preview-customer">{{ currentCustomerName || '系统用户' }}</p>
              <p class="preview-gender">
                <el-icon v-if="form.gender === 'male'" class="gender-icon male"><Male /></el-icon>
                <el-icon v-else class="gender-icon female"><Female /></el-icon>
                {{ form.gender === 'male' ? '男' : '女' }}
              </p>
              
              <div class="preview-tags">
                <el-tag :type="form.status === 'enabled' ? 'success' : 'danger'" size="small">
                  {{ form.status === 'enabled' ? '启用' : '禁用' }}
                </el-tag>
              </div>
              
              <div class="preview-contact" v-if="form.email || form.mobile">
                <p v-if="form.email" class="contact-item">
                  <el-icon><Message /></el-icon>
                  {{ form.email }}
                </p>
                <p v-if="form.mobile" class="contact-item">
                  <el-icon><Phone /></el-icon>
                  {{ form.mobile }}
                </p>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 操作历史 -->
        <el-card class="history-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon><Clock /></el-icon>
              <span>最近操作</span>
            </div>
          </template>
          
          <el-timeline>
            <el-timeline-item timestamp="刚刚" color="#409eff">
              开始编辑用户信息
            </el-timeline-item>
            <el-timeline-item
              v-if="originalData.updatedAt"
              :timestamp="formatDateTime(originalData.updatedAt)"
              color="#67c23a"
            >
              最后一次修改
            </el-timeline-item>
            <el-timeline-item
              v-if="originalData.createdAt"
              :timestamp="formatDateTime(originalData.createdAt)"
              color="#909399"
            >
              创建用户
            </el-timeline-item>
          </el-timeline>
        </el-card>

        <!-- 安全提示 -->
        <el-card class="tips-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon><InfoFilled /></el-icon>
              <span>编辑提示</span>
            </div>
          </template>
          
          <el-alert
            title="安全提示"
            type="warning"
            :closable="false"
            show-icon
          >
            <ul class="tips-list">
              <li>用户名创建后无法修改</li>
              <li>禁用用户将无法登录系统</li>
              <li>修改角色将影响用户权限</li>
              <li>请谨慎操作管理员账户</li>
            </ul>
          </el-alert>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  ArrowLeft, Edit, View, Document, User, Phone, UserFilled, Setting,
  Check, RefreshLeft, Close, Message, Clock, InfoFilled, Avatar, Lock, Picture,
  Upload, Delete, Male, Female
} from '@element-plus/icons-vue';
import UserAPI from '@/api/system/user.api';
import FileAPI from '@/api/file.api';
import { formatDateTime } from '@/utils/date';

const router = useRouter();
const route = useRoute();

// 表单数据
const formRef = ref();
const loading = ref(false);
const submitLoading = ref(false);

const form = reactive({
  id: null,
  username: '',
  password: '',
  mobile: '',
  email: '',
  gender: 'male',
  roleIds: [], // 改为角色ID数组
  customerId: null,
  status: 'enabled',
  avatar: '',
});

// 原始数据（用于重置和比较）
const originalData = ref({});

// 选项数据
const roleOptions = ref([]);
const customerOptions = ref([]);

// 头像上传相关
const avatarUploadRef = ref();
const uploadAction = '/api/admin/file/upload'; // 根据实际的上传接口调整
const uploadHeaders = {
  'Authorization': `Bearer ${localStorage.getItem('token') || ''}`
};

// 表单验证规则
const rules = {
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  mobile: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  roleIds: [
    { 
      required: true, 
      message: '请选择角色', 
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (!value || value.length === 0) {
          callback(new Error('请选择角色'));
        } else {
          callback();
        }
      }
    }
  ],
  customerId: [
    { 
      required: true, 
      message: '请选择所属客户', 
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (isSystemAdmin.value) {
          callback(); // admin角色不需要验证客户
        } else if (!value) {
          callback(new Error('请选择所属客户'));
        } else {
          callback();
        }
      }
    }
  ],
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  mobile: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
};

// 计算属性
const currentRoleName = computed(() => {
  const role = roleOptions.value.find(r => r.id === form.roleIds[0]); // 取第一个角色
  return role?.name || '';
});

const currentCustomerName = computed(() => {
  const customer = customerOptions.value.find(c => c.id === form.customerId);
  return customer?.name || '';
});

// 是否为系统管理员
const isSystemAdmin = computed(() => {
  const role = roleOptions.value.find(r => r.id === form.roleIds[0]); // 取第一个角色
  console.log('当前角色:', role);
  console.log('角色名称:', role?.name);
  console.log('是否为admin:', role?.name === 'admin');
  return role?.name === 'admin';
});

// 监听角色变化
watch(() => form.roleIds, (newRoleIds) => {
  // 如果选择了系统管理员角色，清空客户选择
  if (newRoleIds && newRoleIds.length > 0) {
    const role = roleOptions.value.find(r => r.id === newRoleIds[0]);
    if (role && role.name === 'admin') {
      form.customerId = null;
    }
  }
}, { deep: true });

// 加载角色列表
const loadRoles = async () => {
  try {
    const res = await UserAPI.getRoles();
    roleOptions.value = res.data || res || [];
  } catch (error) {
    console.error('加载角色列表失败:', error);
  }
};

// 加载客户列表
const loadCustomers = async () => {
  try {
    const res = await UserAPI.getCustomers();
    customerOptions.value = res.data || res || [];
  } catch (error) {
    console.error('加载客户列表失败:', error);
  }
};

// 加载用户详情
const loadUserDetail = async () => {
  loading.value = true;
  try {
    const userId = route.params.id;
    if (!userId) {
      ElMessage.error('用户ID不能为空');
      goBack();
      return;
    }

    const res = await UserAPI.getById(userId);
    let userData = {};
    
    if (res && res.data) {
      userData = res.data;
    } else if (res) {
      userData = res;
    }

    // 保存原始数据
    originalData.value = { ...userData };
    
    // 填充表单
    Object.assign(form, userData);
    
    // 处理角色信息：将roles数组转换为roleIds数组
    if (userData.roles && Array.isArray(userData.roles)) {
      form.roleIds = userData.roles.map(role => role.id);
    } else {
      form.roleIds = [];
    }
  } catch (error) {
    ElMessage.error('加载用户详情失败: ' + (error.message || error));
    console.error('加载用户详情失败:', error);
  } finally {
    loading.value = false;
  }
};

// 头像上传相关函数
const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  const isLt5M = file.size / 1024 / 1024 < 5; // 增加到5MB

  if (!isImage) {
    ElMessage.error('只能上传图片格式的文件!');
    return false;
  }
  if (!isLt5M) {
    ElMessage.error('上传文件大小不能超过 5MB!');
    return false;
  }
  return true;
};

const handleAvatarUpload = async (options) => {
  const { file } = options;
  
  try {
    // 显示上传中状态
    ElMessage.info('正在上传头像到七牛云...');
    
    // 调用文件上传API
    const result = await FileAPI.uploadFile(file, 'qiniu');
    
    console.log('上传API返回结果:', result);
    
    // 处理返回结果 - 根据后端日志，直接返回URL字符串
    if (result && typeof result === 'string' && result.startsWith('http')) {
      // 直接返回URL字符串的情况
      form.avatar = result;
      ElMessage.success('头像上传成功');
      console.log('头像URL已设置:', result);
    } else if (result && result.data) {
      // 返回对象包含data字段的情况
      form.avatar = result.data;
      ElMessage.success('头像上传成功');
      console.log('头像URL已设置:', result.data);
    } else {
      console.error('头像上传失败，返回结果:', result);
      ElMessage.error('头像上传失败');
    }
  } catch (error) {
    console.error('头像上传错误:', error);
    ElMessage.error('头像上传失败: ' + (error.message || error));
  }
};

const removeAvatar = () => {
  form.avatar = '';
  ElMessage.success('头像已删除');
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  
  try {
    // 先进行表单验证
    await formRef.value.validate();
    
    // 额外验证：非admin角色必须选择客户
    if (!isSystemAdmin.value && !form.customerId) {
      ElMessage.error('请选择所属客户');
      return;
    }
    
    await ElMessageBox.confirm(
      '确定要保存用户信息的修改吗？',
      '保存确认',
      {
        confirmButtonText: '确定保存',
        cancelButtonText: '取消',
        type: 'info',
      }
    );
    
    submitLoading.value = true;
    
    // 确保传递给后端的数据结构正确
    const userData = {
      id: form.id,
      username: form.username,
      mobile: form.mobile,
      email: form.email,
      gender: form.gender,
      avatar: form.avatar,
      status: form.status,
      roleIds: form.roleIds, // 改为角色ID数组
      customerId: form.customerId || null,
    };

    // 如果密码不为空，则包含密码字段
    if (form.password && form.password.trim() !== '') {
      userData.password = form.password;
    }
    
    await UserAPI.update(form.id, userData);
    ElMessage.success('用户信息修改成功');
    
    // 跳转到详情页面
    router.push({ path: `/system/user/detail/${form.id}` });
  } catch (error) {
    if (error !== 'cancel') {
      // 如果是表单验证错误，不显示错误消息（Element Plus会自动显示）
      if (error.message && !error.message.includes('验证失败')) {
        ElMessage.error('保存失败: ' + (error.message || error));
      }
    }
  } finally {
    submitLoading.value = false;
  }
};

// 重置表单
const handleReset = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要重置表单吗？所有修改将丢失！',
      '重置确认',
      {
        confirmButtonText: '确定重置',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    
    Object.assign(form, originalData.value);
    formRef.value?.clearValidate();
  } catch (error) {
    // 用户取消，不做处理
  }
};

// 返回列表
const goBack = () => {
  router.push({ path: '/system/user/index' });
};

// 查看详情
const handleView = () => {
  router.push({ path: `/system/user/detail/${form.id}` });
};

// 初始化
onMounted(() => {
  Promise.all([
    loadRoles(),
    loadCustomers(),
    loadUserDetail()
  ]);
});
</script>

<style scoped>
.user-edit {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.header-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.header-icon {
  font-size: 18px;
  color: #409eff;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.form-card {
  border-radius: 8px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #333;
}

.card-header .el-icon {
  font-size: 16px;
  color: #409eff;
}

.user-form {
  padding: 20px 0;
}

.form-section {
  margin-bottom: 30px;
  padding: 20px;
  background: #fafafa;
  border-radius: 8px;
  border-left: 4px solid #409eff;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 20px;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.section-title .el-icon {
  color: #409eff;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.avatar-upload-container {
  display: flex;
  align-items: center;
  gap: 20px;
}

.avatar-preview {
  border: 2px solid #e4e7ed;
  border-radius: 50%;
}

.avatar-upload-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.avatar-uploader {
  display: inline-block;
}

.form-actions {
  text-align: center;
  padding: 30px 0;
  border-top: 1px solid #ebeef5;
  margin-top: 30px;
}

.form-actions .el-button {
  margin: 0 10px;
  min-width: 120px;
}

.preview-card,
.history-card,
.tips-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.user-preview {
  text-align: center;
}

.preview-avatar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  font-weight: 600;
  margin-bottom: 15px;
}

.preview-info h4 {
  margin: 10px 0 5px;
  color: #333;
  font-size: 16px;
}

.preview-role {
  color: #409eff;
  font-weight: 600;
  margin: 5px 0;
}

.preview-customer {
  color: #67c23a;
  margin: 5px 0;
}

.preview-gender {
  color: #909399;
  font-size: 14px;
  margin: 5px 0;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
}

.gender-icon {
  font-size: 16px;
}

.gender-icon.male {
  color: #409eff;
}

.gender-icon.female {
  color: #f56c6c;
}

.preview-tags {
  margin: 10px 0;
}

.preview-tags .el-tag {
  margin: 2px;
}

.preview-contact {
  margin-top: 15px;
  text-align: left;
}

.contact-item {
  display: flex;
  align-items: center;
  gap: 5px;
  margin: 5px 0;
  font-size: 12px;
  color: #666;
}

.tips-list {
  margin: 0;
  padding-left: 20px;
}

.tips-list li {
  margin: 5px 0;
  font-size: 13px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-edit {
    padding: 10px;
  }
  
  .header-content {
    flex-direction: column;
    gap: 10px;
  }
  
  .header-actions {
    width: 100%;
  }
  
  .form-actions .el-button {
    margin: 5px;
    min-width: 100px;
  }
}

/* 动画效果 */
.el-card {
  transition: all 0.3s ease;
}

.el-card:hover {
  box-shadow: 0 2px 20px rgba(0, 0, 0, 0.1);
}

.form-section {
  transition: all 0.3s ease;
}

.form-section:hover {
  background: #f0f2f5;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-select .el-input {
  width: 100%;
}
</style>
